<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    piedata: {
      type: Object,
      required: true
    }
  },
  watch: {
    async piedata() {
      this.initChart()
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          top: '28%',
          left: '72%',
          itemWidth: 16,
          itemHeight: 12,
          itemGap: 10,
          icon: 'circle',
        },
        color: ['#409EFF', '#67C23A', '#FCA855', '#9D53FF', '#F56C6C'],
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: (params) => {
                return `${params.name}: ${params.percent || 0}% (${params.value}天)`;
              },
            },
            labelLine: {
              show: true
            },
            data: [
              { value: this.piedata.normal, name: '正常' },
              { value: this.piedata.abnormal, name: '异常' },
              { value: this.piedata.late, name: '迟到' },
              { value: this.piedata.rest, name: '休息' },
              { value: this.piedata.leave, name: '请假' },
              { value: this.piedata.absenteeism, name: '旷工' },
            ]
          }
        ]
      })
    }
  }
}
</script>
